package cn.yunyichina.provider.sys.service.impl;

import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.iface.entity.cache.SessionInfo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.sys.dao.DeptUserRelationDao;
import cn.yunyichina.provider.sys.dao.ResourceDao;
import cn.yunyichina.provider.sys.dao.RoleResourceRelationDao;
import cn.yunyichina.provider.sys.entity.DeptUserRelation;
import cn.yunyichina.provider.sys.entity.Resource;
import cn.yunyichina.provider.sys.entity.RoleResourceRelation;
import cn.yunyichina.provider.sys.entity.UserRoleRelation;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.commons.StringUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/1/26.
 */
@Service
public class ResourceServiceImpl {

    private static Logger logger = LoggerFactory.getLogger(ResourceServiceImpl.class);

    @Autowired
    private ResourceDao resourceDao;

    @Autowired
    private AccountServiceImpl accountService;

    @Autowired
    private RoleResourceRelationDao resourceRelationDao;

    /**
     * 保存资源
     * @methodName: yyt.sys.resource.save
     * @param data
     * @return
     */
    public Response saveResource(String data){
        Response response =new Response();
        Resource requestVo  = JsonUtils.parseObject(data, Resource.class);

        // 校验RequestVo的数据
//        try {
//            Validator.getInstance().validate(requestVo);
//        } catch (ValidateException ex) {
//            logger.error("error", ex);
//            response.setResultCodeAndMessage("1101", "数据校验失败:" + ex.getMessage() + "！");
//            return response;
//        }

        try{
            //查询是否存在相同编号的资源
            Resource query = new Resource();
            query.setResourceCode(requestVo.getResourceCode());
            List<Resource> list = resourceDao.select(query);
            if(list == null || list.size() == 0){
                //新增应用下的机构
                requestVo.setId(PKGenerator.generateId());
                requestVo.setCreatedTime(DateUtils.dateToString(new Date()));
                requestVo.setEnableFlag((short) 1);
                resourceDao.insert(requestVo);
            }else{
                if(StringUtils.isBlank(requestVo.getId())){
                    response.setResultCodeAndMessage("-1","资源编码已存在，不能新增");
                    return response;
                }
                //更新资源
                requestVo.setId(list.get(0).getId());
                requestVo.setUpdateTime(DateUtils.dateToString(new Date()));
                resourceDao.update(requestVo);
            }
            response.setResultCodeAndMessage("0","保存成功");

        }catch (Exception e){
            response.setResultCodeAndMessage("-1","保存失败" + e.getMessage());
        }
        return  response;
    }


    /**
     * 获取资源树 yyt.sys.resource.tree.list
     * @param data
     * @return
     */
    public Response listResourceTree(String data){
        Response response =new Response();
        Resource requestVo  = JsonUtils.parseObject(data, Resource.class);

        // 校验RequestVo的数据
//        try {
//            Validator.getInstance().validate(requestVo);
//        } catch (ValidateException ex) {
//            logger.error("error", ex);
//            response.setResultCodeAndMessage("1101", "数据校验失败:" + ex.getMessage() + "！");
//            return response;
//        }
        List<String> orderColumns = new ArrayList<String>();
        orderColumns.add("show_orders");

        List<Resource> list = resourceDao.select(requestVo,orderColumns,true);
        // 生成树
        List<Resource> treeList =  generateTree(list);
        response.setResult(JsonUtils.toJsonString(treeList));
        return  response;
    }

    /**
     * 资源列表 yyt.sys.resource.list
     * @param data
     * @return
     */
    public Response listResource(String data){
        Response response =new Response();
        Resource requestVo  = JsonUtils.parseObject(data, Resource.class);

        // 校验RequestVo的数据
//        try {
//            Validator.getInstance().validate(requestVo);
//        } catch (ValidateException ex) {
//            logger.error("error", ex);
//            response.setResultCodeAndMessage("1101", "数据校验失败:" + ex.getMessage() + "！");
//            return response;
//        }

        List<Resource> list = resourceDao.select(requestVo);
        response.setResult(JsonUtils.toJsonString(list));
        return  response;
    }

    /**
     * 删除资源 yyt.sys.resource.delete
     * @param data
     * @return
     */
    public Response deleteResource(String data){
        Response response =new Response();
        Resource requestVo  = JsonUtils.parseObject(data, Resource.class);
        try {
            resourceDao.delete(requestVo);
            response.setResultCodeAndMessage("0", "删除成功");
        }catch (Exception e){
            response.setResultCodeAndMessage("-1", "删除失败");
        }
        return  response;
    }

    /**
     * 根据资源list， 生成树结构
     * @param list
     * @return
     */
    public List<Resource> generateTree(List<Resource> list){
        // 最后的结果
        List<Resource> rootList = new ArrayList<Resource>();
        // 先找到所有的一级菜单
        for (int i = 0; i < list.size(); i++) {
            // 一级菜单没有parentId
            if (StringUtils.isBlank(list.get(i).getParentId()) || list.get(i).getParentId().equals("0")) {
                rootList.add(list.get(i));
            }
        }
        // 为一级菜单设置子菜单，getChild是递归调用的
        for (Resource resource : rootList) {
            resource.setChildren(getChild(resource.getId(), list));
        }
        return rootList;
    }

    /**
     * 递归查找子菜单
     * @param id
     * @param list
     * @return
     */
    private List<Resource> getChild(String id, List<Resource> list) {
        // 子资源
        List<Resource> childList = new ArrayList<>();
        for (Resource resource : list) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (!StringUtils.isBlank(resource.getParentId())) {
                if (resource.getParentId().equals(id)) {
                    childList.add(resource);
                }
            }
        }
        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }

        // 把子菜单的子菜单再循环一遍
        for (Resource subRes : childList) {// 没有url子菜单还有子菜单
            // 递归
            subRes.setChildren(getChild(subRes.getId(), list));
        }
        return childList;
    }

    /**
     * 获取用户菜单树 yyt.sys.resource.menu.tree.list
     * @param data
     * @return
     */
    public Response listResourceMenuTree(String data,String sessionId){
        Response response =new Response();

        SessionInfo sessionInfo = CacheService.getSessionInfo(sessionId);
        if(sessionInfo == null || StringUtils.isBlank(sessionInfo.getInsuranceLoginName())){
            response.setResultCodeAndMessage("-1","用户未登录或已超时，请先登录");
            return response;
        }
        String userId = sessionInfo.getUserId();

        List<UserRoleRelation> roleRelations = accountService.ListUserRoleByUserId(userId);
        if(CollectionUtils.isEmpty(roleRelations)){
            response.setResultCodeAndMessage("-1","当前登录用户未分配角色");
            return response;
        }
        List<String> roleIds = new ArrayList<>();
        for(UserRoleRelation roleRelation:roleRelations){
            roleIds.add(roleRelation.getRoleId());
        }
        List<RoleResourceRelation> resourceRelations = resourceRelationDao.selectByRoleIds(roleIds);
        if(CollectionUtils.isEmpty(resourceRelations)){
            response.setResultCodeAndMessage("-1","当前登录用户角色未分配资源");
            return response;
        }

        List<String> resourceIds = new ArrayList<>();
        for(RoleResourceRelation roleResourceRelation:resourceRelations){
            resourceIds.add(roleResourceRelation.getResourceId());
        }

        Map<String,Object> map = new HashedMap();
        map.put("ids",resourceIds);
        map.put("resourceType","1");
        List<Resource> list = resourceDao.selectConditionByIds(map);

        List<Resource> allList = new ArrayList<>();
        allList = removeDuplicate(allList);

        for(Resource resource :list){
            allList.addAll(resourceDao.listResourceByLeaf(resource.getId()));
        }

        // 生成树
        List<Resource> treeList =  generateTree(allList);
        response.setResult(JsonUtils.toJsonString(treeList));
        return  response;
    }


    /**
     * 获取用户资源医院 yyt.sys.resource.hospital.list
     * @param data
     * @return
     */
    public Response listResourceHospital(String data,String sessionId){
        Response response =new Response();

//        SessionInfo sessionInfo = CacheService.getSessionInfo(sessionId);
//        if(sessionInfo == null || StringUtils.isBlank(sessionInfo.getInsuranceLoginName())){
//            response.setResultCodeAndMessage("-1","用户未登录或已超时，请先登录");
//            return response;
//        }
        String userId = "3d9eca70259d11e88a5500163e00065f" ;//sessionInfo.getUserId();


        List<UserRoleRelation> roleRelations = accountService.ListUserRoleByUserId(userId);
        if(CollectionUtils.isEmpty(roleRelations)){
            response.setResultCodeAndMessage("-1","当前登录用户未分配角色");
            return response;
        }
        List<String> roleIds = new ArrayList<>();
        for(UserRoleRelation roleRelation:roleRelations){
            roleIds.add(roleRelation.getRoleId());
        }
        List<RoleResourceRelation> resourceRelations = resourceRelationDao.selectByRoleIds(roleIds);
        if(CollectionUtils.isEmpty(resourceRelations)){
            response.setResultCodeAndMessage("-1","当前登录用户角色未分配资源");
            return response;
        }

        List<String> resourceIds = new ArrayList<>();
        for(RoleResourceRelation roleResourceRelation:resourceRelations){
            resourceIds.add(roleResourceRelation.getResourceId());
        }
        Map<String,Object> map = new HashedMap();
        map.put("ids",resourceIds);
        map.put("resourceType","2");

        List<Resource> list = resourceDao.selectConditionByIds(map);
        response.setResult(JsonUtils.toJsonString(list));
        return  response;
    }


    //删除list重复元素
    public static List<Resource> removeDuplicate(List<Resource> list){
        for  ( int  i  =   0 ; i  <  list.size()  -   1 ; i ++ )  {
            for  ( int  j  =  list.size()  -   1 ; j  >  i; j -- )  {
                if  (list.get(j).getId().equals(list.get(i).getId()))  {
                    list.remove(j);
                }
            }
        }
        return list;
    }

}
